package com.project.controller;

import com.project.bean.BuyCarBean;
import com.project.bean.ProductBean;
import com.project.bean.UserBean;
import com.project.service.IBuyCarService;
import com.project.service.IProductService;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("buyCar")
public class BuyCarController {
    @Autowired
    private IBuyCarService service;
    @Autowired
    private IProductService productService;

    @RequestMapping("findByUserId")
    public List<BuyCarBean> findByUserId(Integer userId) {
        return service.findByUserId(userId);
    }

    @RequestMapping("delById")
    public String delById(Integer id) {
        service.delById(id);
        return "ok";
    }

    @RequestMapping("update")
    public String update(Integer id, Integer price, Integer num) {
        service.update(id, price, num);
        return "ok";
    }

    @RequestMapping("add")
    public String add(BuyCarBean buyCar, String isAdd, @RequestParam(value = "imgPath",required = false) MultipartFile mf) throws IOException {
        //通过商品ID查询购物车记录
        BuyCarBean buyCarBean = service.findByProductId(buyCar.getProductId(), buyCar.getUserId());
        //购物车没有此商品
        if (buyCarBean == null) {
            String fileName="";
            //库存没有此商品  添加库存的商品信息
            if ("isAdd".equals(isAdd)) {
                if (!mf.isEmpty()) {//判断用户是否上传文件
                    //得到上传文件
                    fileName= mf.getOriginalFilename();
                    File dir = new File("D:/上课/java/project0227/jinXiaoCun/src/main/resources/productImg");
                    if (!dir.exists()) {//如果该文件不存在
                        dir.mkdirs();//创建该文件
                    }
                    //重命名文件
                    fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
                    //将上传文件的二进制数据，保存在服务器本地文件中
                    mf.transferTo(new File("D:/上课/java/project0227/jinXiaoCun/src/main/resources/productImg/" + fileName));
                }
                buyCar.getProduct().setNum(0);
                buyCar.getProduct().setImgPath(fileName);
                productService.add(buyCar.getProduct());
                service.add(buyCar);
            } else {
                //库存有商品，采购车没有此商品，添加采购车
                service.add(buyCar);
            }
        } else {
            //采购车有此商品，修改数量
            service.updateAdd(buyCar);
        }

        return "ok";
    }




}
